import { randomUUID } from '../../../../mapUtils/RandomUtil';
import CONST from '../../../../constant/Common';
import ITool from '../ITool';
import Layer from '../../constant/Layer';

/**
 * 供电范围工具箱
 * @implements {ITool}
 */
class PowerRangeTool extends ITool {
  constructor(_top, _impl) {
    super(_top, _impl);
    this.name = 'PowerRangeTool';
    this.desc = '供电范围工具箱';
    this.id = randomUUID();
    this.layeridPrefix = 'PowerRangeTool';
    this.colors = CONST.colors;
    this.colorIndex = 0;
    this.gridTool = '';
    this.dkxDzMap = {};
    this.colorMap = {};
  }

  onAdd() {
    super.onAdd();
    this.init();
  }

  onRemove() {
    super.onRemove();
  }

  /**
   * 初始化
   */
  init() {
    this.initLayer();
    this.getEventBus().$on('gridtool.datachange', () => {
      // this.loadPowerRange(e.features);
    });
  }

  /**
   * 设置电网网架展示工具
   * @param {String} toolname 电网网架展示工具名称
   */
  setGridTool(toolname) {
    this.gridTool = toolname;
  }

  /**
   * 显示供电范围
   */
  show() {
    this.getMap().moveLayer(this._linestringLayerId);
    this.getMap().moveLayer(this._linestringtextLayerId);
    this.getMap().setLayoutProperty(this._linestringLayerId, 'visibility', 'visible');
    this.getMap().setLayoutProperty(this._linestringtextLayerId, 'visibility', 'visible');
  }

  /**
   * 隐藏供电范围
   */
  hide() {
    this.getMap().setLayoutProperty(this._linestringLayerId, 'visibility', 'none');
    this.getMap().setLayoutProperty(this._linestringtextLayerId, 'visibility', 'none');
  }

  /**
   * 加载供电范围
   * @param {*} features 电网数据
   * @ignore
   */
  loadPowerRange(features) {
    let lines = [];
    let dkxoids = new Set();
    features.forEach((item) => {
      if (item.properties.sbzlx * 1 === 10100000 || item.properties.sbzlx * 1 === 20100000) {
        lines.push(item);
        if (!this.dkxDzMap[item.properties.ssdkx]) {
          dkxoids.add(item.properties.ssdkx);
        }
      }
    });
    if (lines.length === 0) {
      this.setData([]);
    } else {
      let dkxsboids = Array.from(dkxoids);
      this.getDkxInfo(dkxsboids).then(() => {
        lines.forEach((line) => {
          line.properties.color = this.getColor(this.dkxDzMap[line.properties.ssdkx]);
        });
        this.setData(lines);
      });
    }
  }

  /**
   * 获取大馈线信息
   * @param {Array} dkxOids 大馈线Id
   * @ignore
   */
  getDkxInfo(dkxOids) {
    return new Promise((resolve) => {
      if (dkxOids.length > 0) {
        let searchOpt = this.getTool(this.gridTool).getSearchOption();
        let params = {
          schema: searchOpt.schema,
          ssghrw: searchOpt.ssghrw,
          cxlx: searchOpt.fxlx,
          verRule: searchOpt.verRule,
          province: CONST.province,
          dkxsboids: dkxOids.join(',')
        };
        if (params.dkxsboids) {
          this.getApi()
            .PwghGhsjJcfw.sbxx.post_sbxx_queryDkxInfo({ params: params })
            .then((res) => {
              // eslint-disable-next-line camelcase
              let { resp_code, datas } = res;
              // eslint-disable-next-line camelcase
              if (resp_code === 200) {
                datas.forEach((item) => {
                  this.dkxDzMap[item.oid] = item.ssdz;
                });
                resolve();
              }
            });
        } else {
          resolve();
        }
      } else {
        resolve();
      }
    });
  }

  /**
   * 加载渲染数据
   * @param {*} features 图形数据
   * @ignore
   */
  setData(features) {
    this.getMap().getSource(this._sourceId).setData(turf.featureCollection(features));
  }

  /**
   * 获取颜色
   * @param {Number} bdzid 变电站Id
   * @ignore
   */
  getColor(bdzid) {
    if (this.colorMap[bdzid]) {
      return this.colorMap[bdzid];
    }
    let color = this.colors[this.colorIndex];
    this.colorMap[bdzid] = color;
    this.colorIndex++;
    if (this.colorIndex >= this.colors.length) {
      this.colorIndex = this.colorIndex - this.colors.length;
    }
    return color;

  }

  /**
   * 初始化图层
   * @ignore
   */
  initLayer() {
    // 初始化数据源
    this._sourceId = this.layeridPrefix + '_source_' + this.id;
    if(!this.getMap().getSource(this._sourceId)) {
      this.getMap().addSource(this._sourceId, {
        type: 'geojson',
        data: {
          type: 'FeatureCollection',
          features: []
        }
      });
    }
    // 初始化图层
    this._linestringLayerId = this.layeridPrefix + '_LineString_' + this.id;
    if(!this.getMap().getLayer(this._linestringLayerId)) {
      this.getMap().addLayer({
        id: this._linestringLayerId,
        type: 'line',
        source: this._sourceId,
        filter: ['all', ['==', 'sourceType', 'LineString']],
        layout: {
          'line-cap': 'round',
          'line-join': 'round',
          'visibility': 'none'
        },
        paint: {
          'line-color': ['get', 'color'],
          'line-width': 3,
          'line-opacity': 1,
          'line-offset': 0
        }
      });
    }
    this._linestringtextLayerId = this.layeridPrefix + '_LineStringText_' + this.id;
    if(!this.getMap().getLayer(this._linestringtextLayerId)) {
      this.getMap().addLayer({
        id: this._linestringtextLayerId,
        type: 'symbol',
        source: this._sourceId,
        filter: ['all', ['==', 'sourceType', 'LineString']],
        layout: {
          'symbol-placement': 'line',
          'icon-ignore-placement': true,
          'icon-anchor': 'center',
          'text-field': '{' + Layer.GlobalMarkLabelField + '}',
          'text-size': 12,
          'text-font': ['Microsoft YaHei Regular'],
          'text-offset': [0, 0],
          'text-max-width': 8,
          'text-allow-overlap': false,
          'text-ignore-placement': false,
          'visibility': 'none'
        },
        paint: {
          'text-color': ['get', 'color'],
          'text-halo-color': '#FFFFFF',
          'text-halo-width': 1.33333
        }
      });
    }
  }
}

export default PowerRangeTool;
